﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Globalization;
using System.Threading;

namespace OutSource.Common.MarketSense
{
    public class MarketSense
    {
        private static CultureInfo _defaultMkt;
        private static CultureInfo[] _allMkt;

        public static void Init(string defaultMkt, string[] allMkt)
        {
            _defaultMkt = new CultureInfo(defaultMkt);

            _allMkt = new CultureInfo[allMkt.Length];

            for(int i = 0; i < _allMkt.Length; i++)
            {
                _allMkt[i] = new CultureInfo(allMkt[i]);
            }
        }

        public static CultureInfo GetCurrentCulture(CultureInfo currentUserCulture, HttpContext httpContext)
        {
            try
            {
                string mkt = httpContext.Request["mkt"];

                if (!string.IsNullOrEmpty(mkt))
                {
                    return new CultureInfo(mkt);
                }

                if (currentUserCulture != null)
                {
                    return currentUserCulture;
                }

                if (httpContext.Request.UserLanguages.Length > 0)
                {
                    return _allMkt.First(
                                (culture) =>
                                {
                                    return culture.Name.Equals(
                                        httpContext.Request.UserLanguages[0],
                                        StringComparison.OrdinalIgnoreCase);
                                });
                }

                return _defaultMkt;
            }
            catch (ArgumentException)
            {
            }
            catch (InvalidOperationException)
            {
            }

            return _defaultMkt;
        }

        public static void InitCurrentCulture(CultureInfo culture)
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }

        public static CultureInfo CurrentMarket
        {
            get
            {
                return Thread.CurrentThread.CurrentUICulture;
            }
        }
    }
}
